package com.ikingtech.framework.sdk.cmd.cmder;

import com.ikingtech.framework.sdk.cmd.CmdTracer;
import com.ikingtech.framework.sdk.context.exception.FrameworkException;
import com.ikingtech.framework.sdk.utils.Tools;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

/**
 * @author tie yan
 */
@Slf4j
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class WorkDirectory {

    public static void clear(File dir) {
        if (dir.isDirectory()) {
            File[] subFiles = dir.listFiles();
            if (Tools.Array.isNotBlank(subFiles)) {
                for (File subFile : subFiles) {
                    clear(subFile);
                }
            }
        }
        try {
            Files.delete(Paths.get(dir.getAbsolutePath()));
        } catch (IOException e) {
            CmdTracer.trace(Tools.Str.format("work directory/file {} remove fail", dir));
        }
    }

    public static void init(String applicationId, String baseDirPath, String... dirPaths) {
        File baseDir = new File(baseDirPath);
        if (!baseDir.mkdirs()) {
            throw new FrameworkException(Tools.Str.format("创建工作目录失败！[{}][{}]", applicationId, baseDirPath));
        }
        for (String dirPath : dirPaths) {
            File subDir = new File(dirPath);
            if (!subDir.mkdirs()) {
                clear(baseDir);
                throw new FrameworkException(Tools.Str.format("创建工作目录失败！[{}][{}]", applicationId, dirPath));
            }
        }
    }
}
